package xx.iverson.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xx.iverson.enums.EnumException;
import xx.iverson.result.ReturnResult;
import xx.iverson.util.WeatherUtil;

import java.io.IOException;

/**
 * xx.iverson.controller.UtilsController
 * 描述：工具接口
 * on 2025/6/26-下午4:14
 *
 * @author weijx
 */

@RestController
@RequestMapping("/api/utils")
public class UtilsController {

    /**
     * 获取客户端真实IP地址并根据IP地址获取所在地以及天气
     *
     * @param request HttpServletRequest对象
     * @return IP地址信息
     */
    @GetMapping("/weather")
    public ReturnResult<?> getClientWeather(HttpServletRequest request) throws IOException {
        String ip = WeatherUtil.getIp(request);
        if (ip == null|| "127.0.0.1".equals(ip)){
            return ReturnResult.error(EnumException.USER_GET_ERROR_IP.getErrorCode(),
                    EnumException.USER_GET_ERROR_IP.getErrorMsg(), null);
        }
        String address = WeatherUtil.getAddress(ip);
        if (address == null){
            return ReturnResult.error(EnumException.USER_GET_ERROR_ADDRESS.getErrorCode(),
                    EnumException.USER_GET_ERROR_ADDRESS.getErrorMsg(), null);
        }
        String weather = WeatherUtil.getWeather(address);
        if (weather == null){
            return ReturnResult.error(EnumException.USER_GET_ERROR_WEATHER.getErrorCode(),
                    EnumException.USER_GET_ERROR_WEATHER.getErrorMsg(), null);
        }
        return ReturnResult.success("获取成功", weather);
    }
}